package com.rimi.bbs.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.rimi.bbs.bean.Card;
import com.rimi.bbs.bean.CardStatus;
import com.rimi.bbs.bean.JsonResult;
import com.rimi.bbs.bean.Replies;
import com.rimi.bbs.service.CardService;
import com.rimi.bbs.service.RepliesService;
import com.rimi.bbs.util.IntegerUtils;
import com.wf.captcha.utils.CaptchaUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;
import java.util.UUID;

/**
 * <p>
 *  前端控制器
 *  card 控制层 为了与前台页面对应 请求地址  叫 jie
 * </p>
 *
 * @author jerry
 * @since 2019-02-24
 */
@Controller
@RequestMapping("/jie")
public class CardController {

    private Logger logger= LoggerFactory.getLogger(getClass());

    @Autowired
    private CardService cardService;

    @Autowired
    private RepliesService repliesService;

    /**
     * @return
     * 帖子状态修改方法
     */
    @PostMapping("/set")
    @ResponseBody
    public Object set(Integer id,String field,Integer rank){
        if(StringUtils.isEmpty(field)){
            return JsonResult.error("服务器异常");
        }
        Card card = cardService.getById(id);
        if(card==null){
            return JsonResult.error("该帖不存在");
        }
        boolean b=false;
        //置顶
        if("stick".equals(field)){
            b = cardService.updateById(card.setCardTop(rank));
        }
        //加精
        if("status".equals(field)){
            b = cardService.updateById(card.setCardEssence(rank));
        }
        if(b){
            return JsonResult.ok("操作成功");
        }
        return JsonResult.error("帖子状态修改失败");
    }

    @GetMapping("/add.html")
    public String addHtml(Model model, HttpSession session){
        logger.info("添加页面 生成token");
        //生成唯一的token,防止表单重复提交
        String uuid = UUID.randomUUID().toString().substring(0, 10);
        session.setAttribute("formtoken",uuid);
        model.addAttribute("page","jie");
        return "/jie/add";
    }

    /**
     * @param cardId
     * @param model
     * @return
     * 准备修改帖子信息
     */
    @GetMapping("/edit/{cardId}")
    public String edit(@PathVariable Integer cardId,Model model){
        Card card = cardService.getCardById(cardId);
        if(card==null){
            return "/other/404";
        }
        model.addAttribute("card",card);
        return "/jie/edit";
    }

    /**
     * @param card 帖子信息
     * @param vercode 验证码
     * @param request request对象
     * @return
     *  返回josn信息
     */
    @PostMapping("/add")
    @ResponseBody
    public  Object add(Card card, String vercode, HttpServletRequest request,HttpSession session,String formtoken){
        //比较表单是否重复提交
        if(StringUtils.isEmpty(formtoken)){
            return JsonResult.error("请勿重复提交表单");
        }
        //
        Object sessionToken= session.getAttribute("formtoken");
        if(StringUtils.isEmpty(sessionToken)){
            return JsonResult.error("请勿重复提交表单");
        }
        //比较token
        if(!sessionToken.equals(formtoken)){
            return JsonResult.error("请勿重复提交表单");
        }
        //移除session中的token信息
        session.removeAttribute("token");
        //验证码比较
        if (!CaptchaUtil.ver(vercode, request)) {
            logger.info("vercode"+vercode);
            CaptchaUtil.clear(request);
            return JsonResult.error("验证码不正确");
        }
        if(card==null){
            return JsonResult.error("请填写帖子信息");
        }
        //判断帖子标题是否重复
        Card one = cardService.getOne(new QueryWrapper<Card>()
                .eq("card_title",card.getCardTitle()));
        logger.info("帖子是否重复"+one);
        if(one!=null){
            return JsonResult.error("该标题已被使用,请修改");
        }
        card.setCardCreateTime(LocalDateTime.now());
        logger.info("帖子信息："+card);
        boolean save = cardService.save(card);
        if(save){
            return JsonResult.okHome("发帖成功");
        }
        return JsonResult.error("发帖失败，请重试");
    }

    /**
     * @param card 帖子信息
     * @param vercode 验证码
     * @param request request对象
     * @return
     *  返回josn信息
     */
    @PostMapping("/edit")
    @ResponseBody
    public  Object edit(Card card, String vercode, HttpServletRequest request){
        //验证码比较
        if (!CaptchaUtil.ver(vercode, request)) {
            logger.info("vercode"+vercode);
            CaptchaUtil.clear(request);
            return JsonResult.error("验证码不正确");
        }
        if(card==null){
            return JsonResult.error("请填写帖子信息");
        }
        boolean save = cardService.updateById(card);
        if(save){
            return JsonResult.okHome("修改帖子成功");
        }
        return JsonResult.error("修改失败，请重试");
    }

    /**
     * @param id
     * @param model
     * @return
     * 通过ID查询帖子详情
     */
    @GetMapping("/detail/{id}")
    public String  getJieById(@PathVariable Integer id,Model model,@RequestParam(defaultValue = "1") Integer nowPage,@RequestParam(defaultValue = "10") Integer pageSize){
        Card card = cardService.getCardById(id);
        if(card==null){
            return "/other/404";
        }
        model.addAttribute("card",card);
        model.addAttribute("page","jie");
        IPage<Replies> repliesList = repliesService.getRepliesList(id,nowPage, pageSize);
        model.addAttribute("repliesList",repliesList.getRecords());
        model.addAttribute("count",repliesList.getTotal());
        model.addAttribute("curr",nowPage);
        //查看次数增加
        cardService.updateById(new Card(id,card.getCardLookNumber()+1));
        return "/jie/detail";
    }


    @RequestMapping("/q/{cardType}")
    public String jieIndex(@PathVariable Integer cardType, Model model,@RequestParam(defaultValue = "1") Integer nowPage,@RequestParam(defaultValue = "10") Integer pageSize){
        IPage<Card> cardList=null;
        //帖子类型
        if(!IntegerUtils.isNotEmptyAndNotZero(cardType)){
            cardList = cardService.getCardList(null, nowPage, pageSize);
        }
        Card card=new Card();
        card.setCardTypeId(cardType);
        cardList = cardService.getCardList(card, nowPage, pageSize);
        model.addAttribute("cardList",cardList.getRecords());
        model.addAttribute("cardTypeId",cardType);
        model.addAttribute("technicalClass",0);
        model.addAttribute("page","jie");
        model.addAttribute("curr",nowPage);
        model.addAttribute("count",cardList.getTotal());
        return "jie/index";
    }

    @RequestMapping("/q/{cardType}/{technicalClass}")
    public String jieIndex(@PathVariable Integer cardType,@PathVariable Integer technicalClass,Model model,@RequestParam(defaultValue = "1") Integer nowPage,@RequestParam(defaultValue = "10") Integer pageSize){
        Card card=null;
        //帖子类型
        if(IntegerUtils.isNotEmptyAndNotZero(cardType)){
            card = new Card();
            card.setCardTypeId(cardType);
        }
        //技术类型
        if(IntegerUtils.isNotEmptyAndNotZero(technicalClass)){
            if(card==null){
                card = new Card();
            }
            card.setTechnicalId(technicalClass);
        }
        IPage<Card> cardList = cardService.getCardList(card, nowPage, pageSize);
        model.addAttribute("cardList",cardList.getRecords());
        model.addAttribute("cardTypeId",cardType);
        model.addAttribute("technicalClass",technicalClass);
        model.addAttribute("page","jie");
        model.addAttribute("curr",nowPage);
        model.addAttribute("count",cardList.getTotal());
        return "jie/index";
    }

    /**
     * @param cardType 帖子类型 id
     * @param technicalClass 技术类型 id
     * @param cardStatus  帖子状态 已结、未结、精华
     * @return
     */
    @RequestMapping("/q/{cardType}/{technicalClass}/{cardStatus}")
    public String index(Model model,@PathVariable Integer cardType,@PathVariable Integer technicalClass,@PathVariable CardStatus cardStatus,@RequestParam(defaultValue = "1") Integer nowPage,@RequestParam(defaultValue = "10") Integer pageSize){
        Card card = new Card();
        //帖子类型
        if(IntegerUtils.isNotEmptyAndNotZero(cardType)){
            card.setCardTypeId(cardType);
        }
        //技术类型
        if(IntegerUtils.isNotEmptyAndNotZero(technicalClass)){
            card.setTechnicalId(technicalClass);
        }
        //帖子状态
        if(!StringUtils.isEmpty(cardStatus)){
            card.setCardStatus(cardStatus);
        }
        IPage<Card> cardList = cardService.getCardList(card, nowPage, pageSize);
        model.addAttribute("cardList",cardList.getRecords());
        model.addAttribute("cardTypeId",cardType);
        model.addAttribute("technicalClass",technicalClass);
        model.addAttribute("page","jie");
        model.addAttribute("cardStatus",cardStatus.toString());
        model.addAttribute("count",cardList.getTotal());
        model.addAttribute("curr",nowPage);
        return "/jie/index";
    }


}

